import store from '@/storm'

const disabledClick = event => event && event.stopImmediatePropagation()
const hasPermission = {
  install (Vue, options) {
    Vue.directive('has', {
      // inserted (el, binding, vnode) {
      //     let permTypes = vnode.context.$route.meta.permTypes;
      //     if (permTypes&&!permTypes.includes(binding.value)) {
      //         el.parentNode.removeChild(el);
      //     }
      // }
      inserted (el, binding, vnode) {
        const retryCount = 0
        if (!binding.value) { return }
        checkPermission(el, binding, retryCount)
      },
      unbind (el) {
        el.removeEventListener('click', disabledClick)
      }
    })
  }
}

function checkPermission (el, binding, retryCount) {
  const btnPermission = store.getters.btnPermission
  if (btnPermission.length === 0) {
    retryCount++
    if (retryCount > 3) {
      el.classList.add('is-disabled')
      el.addEventListener('click', disabledClick, true)
      return
    }
    const timer = setTimeout(() => {
      clearTimeout(timer)
      checkPermission(el, binding, retryCount)
    }, 200)
    return
  }

  if (typeof binding.value === 'string') {
    if (!btnPermission.includes(binding.value)) {
      el.classList.add('is-disabled')
      el.addEventListener('click', disabledClick, true)
    }
    return
  }
  binding.value = Array.isArray(binding.value) ? binding.value : []
  if (binding.value.length) {
    let result = false
    // eslint-disable-next-line array-callback-return
    binding.value.some((perm) => {
      if (btnPermission.includes(perm)) {
        result = true
        return true
      }
    })
    if (!result) {
      el.classList.add('is-disabled')
      el.addEventListener('click', disabledClick, true)
    }
  } else {
    throw new Error('权限code:[\'code1\',\'code2\']')
  }
}

export default hasPermission
